package com.bawei.club.test.recyclerview

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bawei.club.R
import com.bawei.lib_common.utils.LoggerUtils
import com.bawei.lib_image.GlideApp
import java.util.Collections
import java.util.stream.Collectors

/**
 * @author yaotianxue
 * @description
 * @date 2025/5/29
 */
class MyAdapter(
    private val onImageClick: ((String) -> Unit)? = null,
    private val onLikeClick:((Int) -> Unit)? = null,
    private val onPreload:(()->Unit)? = null,
    private var preloadItemCount:  Int = 0, //预加载偏移量，倒数第几个
): RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    private var scrollState = RecyclerView.SCROLL_STATE_IDLE //滚动状态

    /**
     * 更新状态
     */
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    companion object{
        const val TAG = "MyAdapter"
    }
    private val data:MutableList<MyModel> = mutableListOf()

    fun like(position:Int){
        data[position].isLike = !data[position].isLike
        notifyItemChanged(position,"like") //局部刷新
    }

    /**
     * 使用过DiffUtils局部刷新
     */
    fun setData(newData:MutableList<MyModel>){
        val calculateDiff = DiffUtil.calculateDiff(MyDiffCallBack(data.toList(), newData))//旧数据和新数据,注意不要传引用，使用toList
        data.clear()
        data.addAll(newData)
        calculateDiff.dispatchUpdatesTo(this)

//        data.clear()
//        data.addAll(newData)
//        notifyDataSetChanged()
    }

    /**
     * 追加数据，范围局部刷新
     */
    fun addData(newData:MutableList<MyModel>){
        val size = data.size
        data.addAll(newData)
        notifyItemRangeInserted(size-1,newData.size) //范围刷新
    }

    fun addData(myModel: MyModel){
        data.add(myModel)
        notifyItemInserted(data.size) //局部更新
    }
    fun removeData(position:Int){
        data.removeAt(position)
        notifyItemRemoved(position)//局部更新
    }
    fun moveData(from:Int,to:Int){
        Collections.swap(data,from,to)
        notifyItemMoved(from,to)//局部更新
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        LoggerUtils.d(TAG,"onCreateViewHolder: ")
        return MyViewHolder(View.inflate(parent.context, R.layout.item,null))
    }

    override fun getItemCount(): Int {
        return data.size
    }

    /**
     * 判断是否宇加载
     */
    private fun checkPreLoad(position: Int){
        if (onPreload != null && scrollState != RecyclerView.SCROLL_STATE_IDLE && position == data.size - preloadItemCount - 1){
            onPreload.invoke()
        }
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int, payloads: MutableList<Any>) {
        //1-判断是否到达倒数第几个
        checkPreLoad(position)

        if (payloads.isEmpty()){
            super.onBindViewHolder(holder, position, payloads)
        }else{

            when(payloads[0]){
                "like" -> {
                    LoggerUtils.d(TAG,"onBindViewHolder局部增量刷新like: $position")
                    if (data[position].isLike){
                        holder.ivLike.setImageResource(R.drawable.like)
                    }else{
                        holder.ivLike.setImageResource(R.drawable.like_un)
                    }
                }
                "name" ->{
                    LoggerUtils.d(TAG,"onBindViewHolder局部增量刷新name: $position")
                    holder.tv.text = data[position].name
                }
                "url" ->{
                    LoggerUtils.d(TAG,"onBindViewHolder局部增量刷新url: $position")
                    GlideApp.with(holder.itemView).load(data[position].url).into(holder.iv)
                }
            }
        }

    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        LoggerUtils.d(TAG,"onBindViewHolder: $position")
        GlideApp.with(holder.itemView).load(data[position].url).into(holder.iv)
        holder.tv.text = data[position].name
        if (data[position].isLike){
            holder.ivLike.setImageResource(R.drawable.like)
        }else{
            holder.ivLike.setImageResource(R.drawable.like_un)
        }

        //不要在这里设置点击事件，onBindViewHolder多次调用
//        holder.tv.setOnClickListener {
//            onImageClick.invoke(data[position].url)
//        }
    }

    inner class MyViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        val iv: ImageView
        val tv: TextView
        val ivLike:ImageView
        init {
            iv = itemView.findViewById(R.id.iv)
            tv = itemView.findViewById(R.id.tv)
            ivLike = itemView.findViewById(R.id.iv_like)
            //优化四：设置点击事件
            iv.setOnClickListener {
                onImageClick?.invoke(data[bindingAdapterPosition].url)
            }
            ivLike.setOnClickListener {
                onLikeClick?.invoke(bindingAdapterPosition)
            }
        }

    }
}